﻿using UnityEngine;
using System.Collections;

public class EdgeDetectNormalsAndDepth : MonoBehaviour
{

    public Shader edgeDetectShader;
    public Material edgeDetectMaterial;
    public Material material
    {
        get
        {
           // edgeDetectMaterial = CheckShaderAndCreateMaterial(edgeDetectShader, edgeDetectMaterial);
            return edgeDetectMaterial;
        }
    }

    [Range(0.0f, 1.0f)]
    public float edgesOnly = 0.0f;    //调整边缘强度

    public Color edgeColor = Color.black;    //描边颜色

    public Color backgroundColor = Color.white;    //背景色

    public float sampleDistance = 1.0f;    //控制采样距离，值越大，描边越宽

    public float sensitivityDepth = 1.0f;    //深度灵敏度参数

    public float sensitivityNormals = 1.0f;    //法线灵敏度参数
                                               //当灵敏度参数大时，即使深度或法线上很小的变化也会形成一条边

    //由于需要调用摄像机的深度+法线纹理，所以要设置摄像机的相应状态
    void OnEnable()
    {
        GetComponent<Camera>().depthTextureMode |= DepthTextureMode.DepthNormals;
    }

    [ImageEffectOpaque]
    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        if (material != null)
        {
            material.SetFloat("_EdgeOnly", edgesOnly);
            material.SetColor("_EdgeColor", edgeColor);
            material.SetColor("_BackgroundColor", backgroundColor);
            material.SetFloat("_SampleDistance", sampleDistance);
            material.SetVector("_Sensitivity", new Vector4(sensitivityNormals, sensitivityDepth, 0.0f, 0.0f));

            Graphics.Blit(src, dest, material);
        }
        else
        {
            Graphics.Blit(src, dest);
        }
    }
}